<?php
/**
 * job 执行监控中间件.
 * User: dxk
 * Date: 2020-12-22
 */
namespace App\Jobs\Middleware;

use App\Library\Service\DB\TransactionMonitorService;

class EasyJob
{
    public function handle($job, $next)
    {
        define('IS_JOB', 1);
        $start_at = easy_microtime();
        global $EASY_REQUEST_ID;
        $EASY_REQUEST_ID = md5(time() . easy_random(10));
        $res = $next($job);
        if (method_exists($job, 'getParams')) {
            $params = $job->getParams();
        } else {
            $params = [];
        }
        $end_at = easy_microtime();
        $request_log = [
            'trace' => $EASY_REQUEST_ID,
            'job' => get_class($job),
            '入参' => $params,
            '执行用时' => round($end_at - $start_at, 4)
        ];
        if (method_exists($job, 'log')) {
            $log_data = $request_log;
            global $SQL_LOG;
            $log_data['sql_log'] = $SQL_LOG;
            $log_data['执行结果'] = $res;
            $job->log($log_data);
        }
        TransactionMonitorService::requestEnd($request_log);
    }
}